from django.shortcuts import render, HttpResponse
from django.views.decorators.csrf import csrf_exempt

from app.models.delivery import Community, Account, Point
from django.views.decorators.http import require_http_methods
# 引入result.py中定义的数据类型转换工具类和方法
from app.util.result import query_set_to_list, CodeModeDTO, model_to_dict
# Create your views here.


def comm_list(request):
    '''
    所有社区（包括配送点）的信息
    :param request:数据请求
    :return:json数据格式
    '''
    # 查询对象
    communitys = Community.objects.all()
    for community in communitys:
        index = len(community.points) - 1
        while index >= 0:
            p = community.points[index]
            if p.status != "已显示":
                community.points.remove(p)
            index -= 1
    # 转化为数据列表
    communityList = query_set_to_list(communitys)
    index2 = len(communityList) -1
    while index2 >= 0:
        c = communityList[index2]
        size = len(c["points"])
        if size == 0 or c['points'] == []:
            communityList.remove(c)
        index2 -= 1
    # for community in communityList:
    #     size = len(community["points"])
    #     if size == 0 or community["points"] == []:
    #         communityList.remove(community)
    # 规范接口返回格式 即CodeModeDTO（code,message,data）
    #  :param code: int 返回码
    #  :param message: string 返回消息
    #  :param data: obj 返回的数据
    community_a = CodeModeDTO(CodeModeDTO.SUCCESS, '查询成功', communityList)
    # 指定返回类型为json
    return HttpResponse(community_a.to_json(), content_type='application/json,charset=utf-8')


def acc_list(request):
    '''
    所有账户信息
    :param request: 数据请求
    :return:json数据格式
    '''
    # 查询对象
    account = Account.objects.all()
    # 转化为数据列表
    account_change = query_set_to_list(account)
    # 规范接口返回格式 即CodeModeDTO（code,message,data）
    account_a = CodeModeDTO(CodeModeDTO.SUCCESS, '查询成功', account_change)
    # 指定返回类型为json
    return HttpResponse(account_a.to_json(), content_type='application/json,charset=utf-8')


@require_http_methods(["POST", "GET"])
def comm_one(request):
    """
    根据社区ID拿到一条社区实体
    :param request:数据请求
    :return:json数据格式
    """
    # comm_id = ""
    # comms = Community.objects.all()
    # for i in comms:
    #     if comm_id == "":
    #         p = i.points
    #         for j in p:
    #             if j.status == "已隐藏":
    #                 pass
    #             else:
    #                 print(i.id)
    #                 comm_id = i.id
    #                 break
    # print("第一条不隐藏的社区ID是：", comm_id)
    # 查询对象
    communitys = Community.objects.all()
    for community in communitys:
        index = len(community.points) - 1
        while index >= 0:
            p = community.points[index]
            if p.status != "已显示":
                community.points.remove(p)
            index -= 1
    # 转化为数据列表
    communityList = query_set_to_list(communitys)
    index2 = len(communityList) - 1
    while index2 >= 0:
        c = communityList[index2]
        size = len(c["points"])
        if size == 0 or c['points'] == []:
            communityList.remove(c)
        index2 -= 1
    # 规范接口返回格式 即CodeModeDTO（code,message,data）
    community_one = CodeModeDTO(CodeModeDTO.SUCCESS, '查询成功', communityList[0])
    # 指定返回类型为json
    return HttpResponse(community_one.to_json(), content_type='application/json,charset=utf-8')


@require_http_methods(["POST", "GET"])
def acc_one(request):
    """
    根据账户ID拿到一条账户实体
    :param request:数据请求
    :return:json数据格式
    """
    # acc_id = request.GET.get("account_id")
    acc_id = '5b9b2f795e823f46c06624bc' # 测试用的，页面的话用上面一条
    # 根据ID拿出社区实体
    account = Account.objects.get(id=acc_id)
    # 转化为数据列表
    account_change = model_to_dict(account)
    # 规范接口返回格式 即CodeModeDTO（code,message,data）
    account_one = CodeModeDTO(CodeModeDTO.SUCCESS, '查询成功', account_change)
    # 指定返回类型为json
    return HttpResponse(account_one.to_json(), content_type='application/json,charset=utf-8')


@csrf_exempt
@require_http_methods(["POST", "GET"])
def acc_confirm(request):
    """
    根据账户ID拿到一条账户实体
    :param request:数据请求
    :return:json数据格式
    """
    # acc_name = "得删掉" # 测试数据
    # acc_psd = "12112121" # 测试数据
    acc_name = request.GET.get("acc_name")  # 用户名
    acc_psd = request.GET.get("acc_psd")  # 密码
    # 信息
    msg = ""
    # 信息标志码
    code = 0
    # 密码匹配标志
    flag = 0
    # 存社区名字
    comm_name = ""
    # 存放所有的账户名
    alist = []
    # 获取数据库所有的实体
    accounts = Account.objects()
    for i in accounts:
        alist.append(i.user_name)
    if acc_name is None or acc_name is "":
        code = 0
        msg = "用户名为空"
    elif acc_name not in alist:
        code = 2
        msg = "用户名不存在"
    else:
        code = 1
        msg = "用户名存在"
    # 根据用户名拿出社区实体，密码匹配
    if code == 1:
        account = Account.objects.get(user_name=acc_name)
        if account.password == acc_psd:
            flag = 1
            comm_name = account.community_id["name"]
        else:
            flag = 0
    data = {"code": code, "flag": flag, "comm_name": comm_name}
    # 规范接口返回格式 即CodeModeDTO（code,message,data）
    acc_cfirm = CodeModeDTO(CodeModeDTO.SUCCESS, msg, data)
    # 指定返回类型为json
    return HttpResponse(acc_cfirm.to_json(), content_type='application/json,charset=utf-8')